﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using LandPortMoblieWeb.Models;

namespace LandPortMoblieWeb.Service
{
    public class PermissionService:PSIBaseService
    {
        /// <summary>
        /// 得到角色的所有权限
        /// </summary>
        /// <param name="roleId"></param>
        /// <returns></returns>
        public List<Premission> GetPermission(string roleId)
        {
            var result = new List<Premission>();
            var sql = @"select p.permission_id, p.permission_name,p.fid
                        from psi_role_permission r, psi_permission p
                        where r.role_id = @roleId and r.permission_id = p.permission_id
                        order by p.permission_name";
            var p = CreateDbParameters();
            p.AddWithValue("roleId", roleId);
            Query(sql, p, reader =>
            {
                result.Add(new Premission
                {
                    Id = reader.GetString(0),
                    Name = reader.GetString(1),
                    fid = reader.GetString(2),
                });
            });

            return result;
        }
        
        public List<Premission> GetUserPermiss(string uid,string menu)
        {
            var listpre = new List<Premission>();

            var fidstr = new List<string>();
            var str = new StringBuilder("select fid from psi_main_menu where parent_id= (select menu_id from psi_main_menu where menu_caption=@menu_caption and parent_id='') order by show_order");
            var p = CreateDbParameters();
            p.AddWithValue("menu_caption", menu);
            Query(str.ToString(),p,ready =>
            {
                fidstr.Add(ready.GetString(ready.GetOrdinal("fid")));
            });

            var getrolestr = new StringBuilder("select * from psi_user_role where user_id='" + uid + "'");

            var role = "";
            Query(getrolestr.ToString(), ready =>
            {
                role = ready.GetString(ready.GetOrdinal("role_id"));
            });

            if (role == "") return null;

            var cc = GetPermission(role);

            
            if (fidstr.Count < 1) return null;

            foreach (var item in fidstr)
            {
                var result = cc.Where(a => a.fid == item).SingleOrDefault<Premission>();
                if (result != null)
                    listpre.Add(result);
            }

            return listpre;
        }
    }
}